﻿using System.Collections.Generic;

namespace FlashPay.Service.Impl.Sys
{
    using AutoMapper;
    using FlashPay.DAO.Interface;
    using FlashPay.DAO.Sys;
    using FlashPay.Entity.Response.Sys;
    using FlashPay.Service.Sys;
    using FlashPay.Entity.Response.Company;
    using FlashPay.Entity;
    using FlashPay.Entity.Parameter;
    using FlashPay.Entity.Request.Sys;
    using System;
    using FlashPay.EF.Models;
    using FlashPay.Entity.Enum;
    using System.Text.RegularExpressions;
    using FlashPay.DAO.Bank;
    using System.Linq;

    /// <summary>
    /// 系统配置业务实现
    /// </summary>
    public class SysConfigServiceImpl : SysConfigService
    {
        /// <summary>
        /// 系统配置接口
        /// </summary>
        private readonly SysConfigDao _sysConfigDao;

        /// <summary>
        /// 银行数据接口
        /// </summary>
        private readonly BankDao _bankDao;

        /// <summary>
        /// 银行信息数据接口
        /// </summary>
        private readonly BankInfoDAO _bankInfoDao;

        /// <summary>
        /// 公司数据接口
        /// </summary>
        private readonly CompanyDao _companyDao;

        /// <summary>
        /// 日志权限数据接口
        /// </summary>
        private readonly LogDao _logDao;

        /// <summary>
        /// 日志模型
        /// </summary>
        private readonly LogRecord _logRecord;

        /// <summary>
        /// mapper
        /// </summary>
        private readonly IMapper _mapper;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sysConfigDao"></param>
        /// <param name="bankDao"></param>
        /// <param name="mapper"></param>
        public SysConfigServiceImpl(SysConfigDao sysConfigDao, BankDao bankDao,BankInfoDAO bankInfoDao, CompanyDao companyDao, 
            LogDao logDao, LogRecord logRecord, IMapper mapper)
        {
            this._sysConfigDao = sysConfigDao;
            this._bankDao = bankDao;
            this._bankInfoDao = bankInfoDao;
            this._companyDao = companyDao;
            this._logDao = logDao;
            this._logRecord = logRecord;
            this._mapper = mapper;
        }

        /// <summary>
        /// 根据编号获取系统配置
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns>菜单</returns>
        public SysConfigResponse Get(int configId, int companyId)
        {
            var response = new SysConfigResponse();

            var sysConfig = _sysConfigDao.Get(configId);
            if (sysConfig != null)
            {
                response.ConfigId = sysConfig.ConfigId;
                response.ConfigCode = sysConfig.ConfigCode;
                response.ConfigValue = sysConfig.ConfigValue;
                response.ConfigContent = sysConfig.ConfigContent;
                response.CompanyId = sysConfig.CompanyId;
                response.Description = sysConfig.Description;
            }

            #region 公司列表
            var companys = _bankDao.GetCompany(companyId, 2);

            var companyResponse = new List<CompanyResponse>();
            foreach (var item in companys)
            {
                companyResponse.Add(new CompanyResponse()
                {
                    CompanyID = item.CompanyID,
                    CompanyName = item.CompanyName,
                });
            }
            response.CompanyResponse = companyResponse;
            #endregion

            return response;
        }

        /// <summary>
        /// 获取系统配置列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<SysConfigResponse> GetList(SysConfigQuery query)
        {
            var sysConfigResponse = new List<SysConfigResponse>();

            var sysConfigList = _sysConfigDao.GetList(query);
            foreach (var item in sysConfigList) {
                sysConfigResponse.Add(new SysConfigResponse() {
                    ConfigValue = item.ConfigValue,
                    ConfigContent = item.ConfigContent
                });
            }

            return sysConfigResponse;
        }

        /// <summary>
        /// 系统配置新增或编辑
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public JResult AddOrEdit(SysConfigAddOrEditRequest request)
        {
            var result = new JResult()
            {
                Success = false
            };
            try
            {
                if (string.IsNullOrEmpty(request.ConfigCode))
                {
                    throw new Exception("编码不能为空！");
                }

                var configCodeReg = new Regex(@"^[A-Za-z0-9_]+$");
                if (!configCodeReg.IsMatch(request.ConfigCode))
                {
                    throw new Exception("编码由英文、数字包括下划线");
                }

                if (string.IsNullOrEmpty(request.ConfigValue))
                {
                    throw new Exception("值不能为空！");
                }
                var configValueReg = new Regex(@"^[0-9_]+$");
                if (!configValueReg.IsMatch(request.ConfigValue))
                {
                    throw new Exception("值只能为数字");
                }

                if (request.CompanyId <= 0)
                {
                    throw new Exception("请选择公司名称！");
                }

                var sysConfig = new SysConfig()
                {
                    ConfigId = request.ConfigId,
                    ConfigCode = request.ConfigCode,
                    ConfigValue = int.Parse(request.ConfigValue),
                    ConfigContent = request.ConfigContent,
                    CompanyId = request.CompanyId,
                    Description = request.Description,
                };

                if (request.ConfigId > 0)
                {

                    var updateStatus = _sysConfigDao.Update(sysConfig);
                    if (updateStatus)
                    {
                        //日志
                        _logRecord.LogType = LogRecordLogType.SysConfig_Update.GetHashCode();
                        _logRecord.LogLevel = (sbyte)LogLevel.Success.GetHashCode();
                        _logRecord.CreateDate = DateTime.Now;
                        _logRecord.LogRemark = string.Format("编辑系统配置成功,权限编号：{0}", sysConfig.ConfigId);
                        _logDao.Insert(_logRecord);

                        result.Success = true;
                    }
                    else
                    {
                        throw new Exception("编辑权限失败");
                    }
                }
                else
                {
                    var configId = _sysConfigDao.Add(sysConfig);
                    if (configId > 0)
                    {
                        _logRecord.LogType = LogRecordLogType.SysConfig_Add.GetHashCode();
                        _logRecord.LogLevel = (sbyte)LogLevel.Success.GetHashCode();
                        _logRecord.CreateDate = DateTime.Now;
                        _logRecord.LogRemark = string.Format("新增系统配置成功,权限编号：{0}", configId);
                        _logDao.Insert(_logRecord);
                        //日志
                        result.Success = true;
                    }
                    else
                    {
                        throw new Exception("新增系统配置失败");
                    }
                }
            }
            catch (Exception ex)
            {
                try
                {
                    _logRecord.LogType = request.ConfigId > 0 ? LogRecordLogType.SysConfig_Update.GetHashCode() : LogRecordLogType.SysConfig_Add.GetHashCode();
                    _logRecord.LogLevel = (sbyte)LogLevel.Error.GetHashCode();
                    _logRecord.CreateDate = DateTime.Now;
                    _logRecord.LogRemark = string.Format("{0}系统配置失败：{1}", request.ConfigId > 0 ? "编辑" : "新增", ex.Message);
                    _logDao.Insert(_logRecord);
                    //日志
                    result.ErrorMessage = ex.Message;
                }
                catch
                {
                    result.ErrorMessage = ex.Message;
                }
            }

            return result;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="configId"></param>
        /// <returns></returns>
        public JResult Delete(int configId)
        {
            var response = new JResult()
            {
                Success = false
            };
            var status = _sysConfigDao.Delete(configId);
            if (status)
            {
                _logRecord.LogType = LogRecordLogType.SysConfig_Delete.GetHashCode();
                _logRecord.LogLevel = (sbyte)LogLevel.Success.GetHashCode();
                _logRecord.CreateDate = DateTime.Now;
                _logRecord.LogRemark = string.Format("删除系统配置成功,权限编号：{0}", configId);
                _logDao.Insert(_logRecord);
                response.SuccessMessage = "操作成功！";
                response.Success = true;
            }
            else
            {
                _logRecord.LogType = LogRecordLogType.SysConfig_Delete.GetHashCode();
                _logRecord.LogLevel = (sbyte)LogLevel.Failure.GetHashCode();
                _logRecord.CreateDate = DateTime.Now;
                _logRecord.LogRemark = string.Format("删除系统配置失败,权限编号：{0}", configId);
                _logDao.Insert(_logRecord);
                response.ErrorMessage = "操作失败！";
                response.Success = false;
            }
            return response;
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>PagedList<SysConfig></returns>
        public PagedList<SysConfigResponse> GetPager(SysConfigQuery query)
        {
            if (query.CompanyId.HasValue)
            {
                query.CompanyIds = CompanyIDList(query.CompanyId.Value);
                query.CompanyId = null;
            }
            var pager = _sysConfigDao.GetPager(query);
            return pager;
        }

        /// <summary>
        /// 获取第三方接口列表
        /// </summary>
        public PagedList<PaymentInterfaceNew> GetPayMentInterfaceList(PaymentInterfaceQuery query)
        {
            //if (query.CompanyId.HasValue)
            //{
            //    query.CompanyIds = CompanyIDList(query.CompanyId.Value);
            //    query.CompanyId = null;
            //}

            var companyIds = _bankDao.GetCompanyIDList(query.CompanyId.Value);
            if (query.SearchCompanyIds != null && query.SearchCompanyIds.Any())
            {
                query.CompanyIds = query.SearchCompanyIds.Where(c => companyIds.Contains(c)).ToList();
                query.CompanyId = null;
            }
            else
            {
                query.CompanyIds = companyIds;
            }

            PagedList<PaymentInterfaceNew> pag = _sysConfigDao.GetPayMentInterfaceList(query);
            if (pag.Success)
            {
                for (int i = 0; i < pag.TData.Count; i++)
                {
                    pag.TData[i].WithdrawalBank = _bankInfoDao.GetBankNameByStr(pag.TData[i].WithdrawalBank);
                    pag.TData[i].PaymentTypeName = _sysConfigDao.GetTransType((int)ReceiptTrans.TranCompanyId, pag.TData[i].PaymentType, "PaymentInterface");

                    if (!query.permission.CanView)
                    {
                        pag.TData[i].SecretKey = "******";
                    }
                }
            }
            pag.permission = query.permission;
            return pag;
        }

        /// <summary>
        /// 获取某第三方接口详细信息
        /// </summary>
        public JResult<PaymentInterface> GetDetail(PaymentInterfaceQuery query)
        {
            var response = new JResult<PaymentInterface>()
            {
                Success = false
            };

            if (query.CompanyId <= 0)
            {
                response.ErrorMessage = "获取参数失败";
                return response;
            }
            try
            {
                response.Data = _sysConfigDao.GetDetail(query);
            }
            catch (Exception ex)
            {
                response.ErrorMessage = "系统异常" + ex.Message;
                return response;
            }

            response.Success = true;
            return response;
        }

        /// <summary>
        /// 获取某第三方接口多重信息
        /// </summary>
        public JResult<PaymentInterfaceMany> GetManyInfo(PaymentInterfaceQuery query)
        {
            var response = new JResult<PaymentInterfaceMany>()
            {
                Success = false
            };
            if (query.CompanyId <= 0)
            {
                response.ErrorMessage = "获取参数失败";
                return response;
            }
            try
            {
                PaymentInterfaceMany pInterface = new PaymentInterfaceMany();
                List<int> CompanyIds = CompanyIDList(query.CompanyId.Value);
                pInterface.CompanyList = _companyDao.GetCompanyListByIds(CompanyIds);   //公司列表
                pInterface.BankList = _bankInfoDao.GetBankInfoList();//银行卡列表
                pInterface.SysConfigTypeList = _sysConfigDao.GetTransTypeList(
                    new SysConfigAddOrEditRequest { ConfigCode = "PaymentInterface" });//配置列表
                pInterface.PaymentInterface = _sysConfigDao.GetDetail(query); //详细信息
                response.ErrorCode = query.permission.CanView.ToString().ToLower();
                response.Data = pInterface;
            }
            catch (Exception ex)
            {
                response.ErrorMessage = "系统异常" + ex.Message;
                AddLog((SByte)LogLevel.Success, (Int32)LogRecordLogType.SysInterface_Get, ex.Message, "获取第三方接口详细信息出错");
                return response;
            }
            response.Success = true;
            return response;
        }

        /// <summary>
        /// 添加或修改
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public JResult AddOrEditInterface(PaymentInterfaceQuery request)
        {
            var response = new JResult()
            {
                Success = false
            };
            if (request == null)
            {
                response.ErrorMessage = "参数不能为空";
                return response;
            }
            int rows = 0;
            if (request.Type == 1)
            {
                rows = _sysConfigDao.EditInterface(request);
            }
            else
            {
                rows = _sysConfigDao.AddInterface(request);
            }
            if (rows >= 0)
            {
                response.Success = true;
                response.SuccessMessage = "操作成功";
                AddLog((SByte)LogLevel.Success, (Int32)LogRecordLogType.SysInterface_Update, request, "更新第三方接口信息成功");
            }
            else if (rows == -1)
            {
                response.ErrorMessage = "信息获取失败";
            }
            else if (rows == -2)
            {
                response.ErrorMessage = "已存在相同接口类型的数据";
            }
            else if (rows == -3)
            {
                response.ErrorMessage = "修改第三方接口信息时发生服务器错误";
            }
            return response;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="configId"></param>
        /// <returns></returns>
        public JResult DeleteInterface(PaymentInterfaceQuery request)
        {
            var response = new JResult()
            {
                Success = false
            };
            int rows = _sysConfigDao.DeleteInterface(request);
            if (rows > 0)
            {
                response.Success = true;
                response.SuccessMessage = "删除成功";
                AddLog((SByte)LogLevel.Success, (Int32)LogRecordLogType.SysInterface_Delete, request, "删除成功");
            }
            else if (rows == -1)
            {
                response.ErrorMessage = "信息获取失败";
            }
            else
            {
                response.ErrorMessage = "删除失败";
                AddLog((SByte)LogLevel.Failure, (Int32)LogRecordLogType.SysInterface_Delete, request, "删除失败");
            }
            return response;
        }

        /// <summary>
        /// 修改状态
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public JResult UpdateStatus(PaymentInterfaceQuery request)
        {
            var response = new JResult()
            {
                Success = false
            };
            int rows = _sysConfigDao.UpdateStatus(request);
            if (rows > 0)
            {
                response.Success = true;
                response.SuccessMessage = "操作成功";
                AddLog((SByte)LogLevel.Success, (Int32)LogRecordLogType.SysInterface_UpdateStatus, request, "更新状态成功");
            }
            else
            {
                response.ErrorMessage = "操作失败";
                AddLog((SByte)LogLevel.Failure, (Int32)LogRecordLogType.SysInterface_UpdateStatus, request, "更新状态失败");
            }
            return response;
        }


        /// <summary>
        /// 获取推送地址列表
        /// </summary>
        public PagedList<ExtApiPushUrl> GetPushAddressList(PushAddressQuery query)
        {
            return _sysConfigDao.GetPushAddressList(query);
        }

        /// <summary>
        /// 获取交易类型信息
        /// </summary>
        public string GetTransType(int companyId, int ConfigValue, string ConfigCode)
        {
            return _sysConfigDao.GetTransType(companyId, ConfigValue, ConfigCode);
        }

        /// <summary>
        /// 获取交易类型列表
        /// </summary>
        public PagedList<SysConfig> GetTransTypeList(SysConfigAddOrEditRequest sysRequest)
        {
            var response = new PagedList<SysConfig>()
            {
                Success = false
            };
            var row = _sysConfigDao.GetTransTypeList(sysRequest);
            if (row != null)
            {
                response.Success = true;
                response.TData = row;
            }
            else
            {
                response.ErrorMessage = "暂无数据";
            }
            return response;
        }

        /// <summary>
        /// 获取交易类型列表
        /// </summary>
        public PagedList<SysConfig> GetTransTypeListNew(SysConfigAddOrEditRequest sysRequest)
        {
            var response = new PagedList<SysConfig>()
            {
                Success = false
            };
            var row = _sysConfigDao.GetTransTypeListNew(sysRequest);
            if (row != null)
            {
                response.Success = true;
                response.TData = row;
            }
            else
            {
                response.ErrorMessage = "暂无数据";
            }
            return response;
        }

        //记录日志
        public void AddLog(sbyte level, int type, Object data, string remark)
        {
            _logRecord.LogLevel = level;
            _logRecord.LogType = type;
            _logRecord.CreateDate = DateTime.Now;
            _logRecord.LogRemark = remark;
            _logRecord.RequestData = Newtonsoft.Json.JsonConvert.SerializeObject(data);
            _logDao.Insert(_logRecord);
        }

        //获取CompanyID集合
        public List<int> CompanyIDList(int companyId)
        {
            return _bankDao.GetCompanyIDList(companyId);
        }

    }
}
